package minha.lista;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Stack;

import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.ListView;
import android.widget.Toast;

public class MinhaListaActivity extends ListActivity
{
  private List<String> fileList = new ArrayList<String>();

  Stack<File> history;

  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);

    history = new Stack<File>();

    File root = new File(Environment.getExternalStorageDirectory()
                                      .getAbsolutePath());
    ListDir(root);

  }

  @Override
  protected void onListItemClick(ListView l, View v, int position, long id)
  {
    // TODO Auto-generated method stub
    File selected = new File(fileList.get(position));
    if (selected.isDirectory())
    {
      ListDir(selected);
    }
    else
    {
      Uri selectedUri = Uri.fromFile(selected);
      String fileExtension = MimeTypeMap
                                        .getFileExtensionFromUrl(selectedUri
                                                                            .toString());
      String mimeType = MimeTypeMap.getSingleton()
                                     .getMimeTypeFromExtension(fileExtension);

      Toast.makeText(MinhaListaActivity.this,
                     "FileExtension: " + fileExtension + "\n" + "MimeType: "
                         + mimeType,
                     Toast.LENGTH_LONG).show();

      // Start Activity to view the selected file
      Intent intent;
      intent = new Intent(Intent.ACTION_VIEW);
      intent.setDataAndType(selectedUri, mimeType);
      startActivity(intent);

    }
  }

  // class to limit the choices shown when browsing to SD card to media files
  public class AudioFilter implements FileFilter
  {

    // only want to see the following audio file types
    private String[] extension =
    { ".mp3", ".wav", ".ogg", ".3gp", ".mp4", ".flac" };

    @Override
    public boolean accept(File pathname)
    {

      // if we are looking at a directory/file that's not hidden we want to see
      // it so return TRUE
      if ((pathname.isDirectory()) && !pathname.isHidden())
      {
        return true;
      }

      // loops through and determines the extension of all files in the
      // directory
      // returns TRUE to only show the audio files defined in the String[]
      // extension array
      for (String ext : extension)
      {
        if (pathname.getName().toLowerCase().endsWith(ext))
        {
          return true;
        }
      }

      return false;
    }
  }

  void ListDir(File f)
  {
    Comparator<? super File> filecomparator = new Comparator<File>()
    {
      @Override
      public int compare(File file1, File file2)
      {
        return String.valueOf(file2.getName()).compareTo(file1.getName());
      }
    };

    history.push(f);

    File[] files = f.listFiles(new AudioFilter());

    Arrays.sort(files, filecomparator);

    fileList.clear();
    for (File file : files)
    {
      fileList.add(file.getPath());
    }

    MySimpleArrayAdapter directoryList = new MySimpleArrayAdapter(this,
                                                                  fileList);

    /*
     * ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,
     * R.layout.mylayout, R.id.mylist, fileList);
     */
    setListAdapter(directoryList);
  }


  @Override
  public void onBackPressed()
  {
    // TODO Auto-generated method stub

    history.pop(); // remove current directory

    if (history.empty())
    {
      super.onBackPressed();
    }
    else
    {
      File selected = history.pop(); // Get the File on Top of history
      ListDir(selected);
    }

  }

}
